<template>
  <div class="menus-manage">
    <!-- 面包屑 -->
    <div class="bread-crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>审批角色</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="main-middle">
      <el-card class="box-card">
        <!-- 查询条件 -->
        <el-row class="table-selbox" v-if="btnSel">
          <!-- 查询条件表单 -->
          <el-form :inline="true" :model="formInline" >
            <el-form-item label="公司">
              <el-select v-model="formInline.compId" @change="compDeplist">
                <el-option label="无" value=""></el-option>
                <el-option v-for="item in compsList" :key="item.compId" :label="item.compName" :value="item.compId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="部门">
              <el-select v-model="formInline.deptId">
                <el-option label="无" value=""></el-option>
                <el-option v-for="ite in depList" :key="ite.deptId" :label="ite.deptName" :value="ite.deptId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色">
              <el-select v-model="formInline.roleId">
                <el-option label="无" value=""></el-option>
                <el-option label="部门总监" value="1"></el-option>
                <el-option label="副总经理" value="2"></el-option>
                <el-option label="总经理" value="3"></el-option>
                <el-option label="EMT分管领导" value="4"></el-option>
                <el-option label="董事长" value="5"></el-option>
              </el-select>
            </el-form-item>
            <!-- 搜索 -->
            <el-form-item>
              <el-button icon="el-icon-search" @click="selHandle">搜索</el-button>
            </el-form-item>
          </el-form>
        </el-row>
        <!-- 基本操作按钮 是否授权显示-->
        <el-row class="table-btns" v-if="[btnAdd,btnDel,btnUpload,btnDown].indexOf(true) > -1">
          <!-- 添加 -->
          <el-button
            v-if="btnAdd"
            type="success"
            size="medium"
            icon="el-icon-document-add"
            @click="addHandle"
          >添加</el-button>
          <!-- 删除 -->
          <el-button
            type="danger"
            size="medium"
            icon="el-icon-delete"
            @click="batchRemove"
            v-if="btnDel"
          >删除</el-button>
        </el-row>
        <!-- 数据列表 -->
        <el-table
          :data="usersData"
          border
          @selection-change="selsChange"
          style="width: 100%"
          height="580"
          ref="usersData"
        >
          <!-- 全选 -->
          <el-table-column type="selection" width="40" fixed></el-table-column>
          <!-- 公司 -->
          <el-table-column :show-overflow-tooltip="true" prop="compName" label="公司" width="150"></el-table-column>
          <!-- 部门 -->
          <el-table-column :show-overflow-tooltip="true" prop="deptName" label="部门" width="150"></el-table-column>
          <!-- 角色 -->
          <el-table-column sortable prop="roleName" label="角色" width="120"></el-table-column>
           <!-- 授权金额 -->
          <el-table-column sortable prop="money" label="授权金额" width="120"></el-table-column>
          <!-- 授权天数 -->
          <!-- <el-table-column sortable prop="daySize" label="授权天数" width="120"></el-table-column> -->
          <!-- 员工工号 -->
          <el-table-column prop="userId" label="工号" width="120"></el-table-column>
          <!-- 员工姓名 -->
          <el-table-column prop="userName" label="姓名" width="120"></el-table-column>
          <!-- 备注说明 -->
          <el-table-column prop="note" label="备注说明" :show-overflow-tooltip="true"></el-table-column>
          <!-- 操作列 -->
          <el-table-column
            label="管理"
            fixed="right"
            align="center"
            width="200"
            v-if="[btnDel,btnEdit].indexOf(true) > -1"
          >
            <template slot-scope="scope">
              <!-- 删除 -->
              <el-button type="danger" size="mini" @click="handleDelete(scope.row)" v-if="btnDel">删除</el-button>
              <!-- 修改 -->
              <el-button size="mini" @click="editHandle(scope.row)" v-if="btnEdit">修改</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="table-pageblock">
          <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[20,50,80,100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </el-card>
      <!-- 弹窗 新增or修改 -->
      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
      <!-- 添加、修改表单 -->
        <el-form ref="editForm" :model="editForm" label-width="80px" :rules="editFormRules">
           <el-row :gutter="24">
             <el-col :span="12">
              <!-- 公司部门选择框子组件 -->
              <el-form-item label="公司部门" prop="compDept">
                <org-tree
                  v-model="editForm.compDept"
                  :compdepts="compdepts"
                  :comps="compsList"
                  :selcpms="selcpmsVal"
                  @selcompdepts="getCompDept"
                ></org-tree>
              </el-form-item>
             </el-col>
             <el-col :span="12">
              <!-- 员工姓名 -->
              <el-form-item label="员工姓名" prop="getUser">
                <!-- 员工选择子组件 -->
                <user-sel :users="users" @seluser="selUser" :sel="sel" v-model="editForm.getUser"></user-sel>
              </el-form-item>
            </el-col>
           </el-row>
           <el-form-item label="角色设定" prop="roleId">
            <el-select v-model="editForm.roleId" style="width:100%;">
              <el-option label="无" value=""></el-option>
              <el-option label="部门总监" value="1"></el-option>
              <el-option label="副总经理" value="2"></el-option>
              <el-option label="总经理" value="3"></el-option>
              <el-option label="EMT分管领导" value="4"></el-option>
              <el-option label="董事长" value="5"></el-option>
            </el-select>
          </el-form-item>
           <el-form-item label="授权金额" prop="money">
            <el-input placeholder="请输入具体金额" v-model="editForm.money" onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')">
              <template slot="prepend">￥</template>
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="授权天数" prop="daySize">
            <el-input placeholder="请输入具体天数" v-model="editForm.daySize" onkeyup="if(this.value=='00'){this.value='0';}else{this.value=this.value.replace(/[^0-9]/g,'')}">
              <template slot="append">天</template>
            </el-input>
          </el-form-item> -->
          <!-- 备注说明 -->
          <el-form-item label="备注说明">
            <el-input
              type="textarea"
              placeholder="备注说明（20字以内）"
              maxlength="20"
              v-model="editForm.note"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <!-- 取消 关闭弹窗 -->
          <el-button @click.native="dialogFormVisible=false">取消</el-button>
          <!-- 添加 清空表单初始数据 -->
          <el-button
            v-if="dialogStatus=='create'"
            type="primary"
            @click="createData"
            :disabled="isSubmit"
          >添加</el-button>
          <!-- 修改获取表单初始数据 -->
          <el-button v-else type="primary" @click="editData" :disabled="isSubmit">修改</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 引入员工选择组件
import userSel from '@/components/UserSel/index.vue';
// 引入公司部门选择组件
import orgTree from '@/components/OrgTree/index.vue';

export default {
  // 注册组件
  components: {
    userSel,
    orgTree
  },

  // 父组件传值子组件
  props: {
    // 按钮级权限
    btns: {
      type: Object
    }
  },

  // 无白屏刷新方法注入
  inject: ['reload'],

  // 监听
  watch: {
    // 按钮权限数据
    btns (val, oldVal) {
      // 刷新当前页
      this.reload();
    }
  },

  // 创建实例后执行
  created () {
    // 按钮级授权
    this.authorization(this.$store.state.btns);

    // 获取所有公司
    this.getComp();

    // 获取所有部门
    this.getDept();

    // 获取所有员工
    this.getUsers();

    // 加载分页数据
    this.getUsersDataByPage();
  },

  // 当前页面数据
  data () {
    return {
      // 避免重复提交
      isSubmit: false,
      // 按钮显示隐藏  - 默认值
      btnSel: true,
      btnDel: true,
      btnUpload: true,
      btnDown: true,
      btnAdd: true,
      btnEdit: true,

      // 获取所有公司
      compsList: [],
      // 获取所有部门
      compdepts: [],

      // 获取所有用户
      users: [],

      // 修改回显用户
      sel: '',

      // 获取公司部门选择框子组件选中值
      compDept: [],
      // 用户选择框子组件选中值
      getUser: [],

      // 根据所选公司获取对应部门
      depList: [],

      // 修改弹窗 - 公司部门子组件默认选中值
      selcpmsVal: [],

      // 搜索条件
      formInline: {
        compId: '',
        deptId: '',
        roleId: ''
      },

      // 列表数据
      usersData: [{}],
      // 当前页
      currentPage: 1,
      // 当前数
      pageSize: 20,
      // 总条目数
      total: 20,

      // 弹窗类别
      dialogStatus: '',

      // 弹窗标题
      textMap: {
        edit: '修改信息',
        create: '添加信息'
      },
      // 弹窗是否显示
      dialogFormVisible: false,

      // 列表选中列
      sels: [],

      // 界面默认数据
      editForm: {
        compDept: [],
        getUser: [],
        role: '',
        money: '',
        // daySize: '',
        note: ''
      },
      // 编辑界面输入框校验规则
      editFormRules: {
        compDept: [{ required: true, message: '请选择公司部门', trigger: 'blur' }],
        getUser: [{ required: true, message: '请选择员工姓名', trigger: 'blur' }],
        roleId: [{ required: true, message: '请选择角色设定', trigger: 'blur' }],
        money: [{ required: true, message: '请填写授权金额', trigger: 'blur' }]
        // daySize: [{ required: true, message: '请填写授权天数', trigger: 'blur' }]
      }
    };
  },
  mounted () {
    // this.getHeight();
    // 增加监听事件，窗口变化时得到高度。
    // window.addEventListener('resize', this.getHeight, false);
  },
  methods: {
    // 表格高度自适应
    // getHeight () {
    // // 获取浏览器高度并计算得到表格所用高度。
    //   this.tableHeight = document.documentElement.clientHeight - 350;
    // },
    // 根据所选公司获取对应部门
    compDeplist () {
      const id = this.formInline.compId;
      this.depList = [];
      this.compdepts.map(item => {
        if (item.compId === id) {
          this.depList.push(item);
        }
      });
    },
    // 按钮级授权
    authorization (data) {
      for (let i in data) {
        if (data['sel'] === 0) {
          this.btnSel = false;
        }
        if (data['add'] === 0) {
          this.btnAdd = false;
        }
        if (data['del'] === 0) {
          this.btnDel = false;
        }
        if (data['upload'] === 0) {
          this.btnUpload = false;
        }
        if (data['down'] === 0) {
          this.btnDown = false;
        }
        if (data['edit'] === 0) {
          this.btnEdit = false;
        }
        return i;
      }
    },

    // 获取所有公司
    getComp () {
      this.$http.post('api/findAllCompNoPage').then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          this.compsList = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取所有部门
    getDept () {
      // 获取部门列表
      this.$http.post('api/findDeptByCompNoPage').then(res => {
        let { code, datas } = res;
        if (code === 0) {
          this.compdepts = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 获取所有用户
    getUsers () {
      let _this = this;
      let params = {
        status: ''
      };
      _this.$http.post('api/findAllBaseUsers', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          _this.users = datas;
        }
      }).catch(err => {
        if (err === undefined) {
          _this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 查询
    selHandle: function () {
      // 收集请求数据
      let params = {
        deptId: this.formInline.deptId,
        compId: this.formInline.compId,
        roleId: this.formInline.roleId,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };
      // 根据员工ID 部门ID 公司ID查询分页数据
      this.$http.raw('api/findTblUserRoleList', params).then(res => {
        let { code, datas } = res;
        // 判断Code状态
        if (code === 0) {
          // 总页数
          this.total = datas.total;
          // 数据结果集
          this.usersData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.currentPage !== 1) {
            // 当前页减一
            this.currentPage -= 1;
            // 调用自己
            this.getUsersDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 显示新增界面
    addHandle: function () {
      let _this = this;
      // 弹窗类型
      _this.dialogStatus = 'create';
      // 弹窗显示状态
      _this.dialogFormVisible = true;
      _this.compDept = '';
      _this.getUser = '';
      // 初始化弹窗表单 公司部门选择框子组件选中数据
      _this.selcpmsVal = [];

      // 所选员工清空
      _this.sel = '';
      // 初始化新增界面默认数据
      _this.editForm = {
        compDept: '',
        getUser: '',
        roleId: '',
        money: '',
        // daySize: '',
        note: ''
      };
    },

    // 获取用户选择框选中值
    selUser (data) {
      let _this = this;
      _this.getUser = data;
      _this.editForm.getUser = data;
    },

    // 获取公司部门选择框选中值
    getCompDept (data) {
      this.compDept = data;
      this.editForm.compDept = data;
      this.editForm.location = data[1];
      this.editForm.getUser = data;
    },

    // 添加
    createData: function () {
      // 防止重复提交
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);
      this.$nextTick(() => {
        // 判断是否通过验证规则验证
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 收集请求参数
            let params = {
              compId: this.editForm.compDept[0],
              compName: this.editForm.compDept[1],
              deptId: this.editForm.compDept[2],
              deptName: this.editForm.compDept[3],
              userId: this.getUser[0],
              userName: this.getUser[3],
              roleId: this.editForm.roleId,
              // daySize: this.editForm.daySize,
              money: this.editForm.money,
              roleName: '',
              note: this.editForm.note
            };
            if (this.editForm.roleId === '1') {
              params.roleName = '部门总监';
            }
            if (this.editForm.roleId === '2') {
              params.roleName = '副总经理';
            }
            if (this.editForm.roleId === '3') {
              params.roleName = '总经理';
            }
            if (this.editForm.roleId === '4') {
              params.roleName = 'EMT分管领导';
            }
            if (this.editForm.roleId === '5') {
              params.roleName = '董事长';
            }
            // 添加用户审批角色
            this.$http.raw('api/insertTblUserRole', params).then(res => {
              let { code, datas } = res;
              // 判断Code状态
              if (code === 0) {
                let type = 'success';
                if (datas.indexOf('成功') > -1) {
                  type = 'success';
                  this.$message({
                    message: datas,
                    type: type
                  });
                  this.$refs['editForm'].resetFields();
                  this.dialogFormVisible = false;
                  // 刷新列表
                  this.getUsersDataByPage();
                  // 获取所有员工
                  this.getUsers();
                } else {
                  type = 'error';
                  this.$message({
                    message: datas,
                    type: type
                  });
                }
              }
            }).catch(err => {
              if (err === undefined) {
                this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    },

    // 显示编辑界面
    editHandle: function (row) {
      // 弹窗类型
      this.dialogStatus = 'edit';
      // 弹窗显示状态
      this.dialogFormVisible = true;

      // 公司部门选择框子组件初始选中值
      this.selcpmsVal = [row.compName, row.deptName];

      // 弹出窗表单初始值赋值
      this.editForm = Object.assign({}, row);
      this.editForm.roleId = row.roleId;
      // 弹出窗表单 - 公司部门选择框子组件初始值赋值
      this.editForm.compDept = [
        row.compId,
        row.compName,
        row.deptId,
        row.deptName
      ];

      this.sel = row.userName;
      this.getUser = [row.userId, row.deptId, row.compId, row.userName];
      this.editForm.getUser = [
        row.compId,
        row.compName,
        row.deptId,
        row.deptName
      ];
    },

    // 修改
    editData: function () {
      // 防止重复提交
      this.isSubmit = true;
      setTimeout(() => {
        this.isSubmit = false;
      }, 1000);

      this.$nextTick(() => {
        // 判断是否通过验证规则验证
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            // 收集请求参数
            let params = {
              id: this.editForm.id,
              compId: this.editForm.compDept[0],
              compName: this.editForm.compDept[1],
              deptId: this.editForm.compDept[2],
              deptName: this.editForm.compDept[3],
              userId: this.getUser[0],
              userName: this.getUser[3],
              roleId: this.editForm.roleId,
              roleName: '',
              note: this.editForm.note,
              // daySize: this.editForm.daySize,
              money: this.editForm.money
            };
            if (this.editForm.roleId === '1') {
              params.roleName = '部门总监';
            }
            if (this.editForm.roleId === '2') {
              params.roleName = '副总经理';
            }
            if (this.editForm.roleId === '3') {
              params.roleName = '总经理';
            }
            if (this.editForm.roleId === '4') {
              params.roleName = 'EMT分管领导';
            }
            if (this.editForm.roleId === '5') {
              params.roleName = '董事长';
            }
            // 修改用户信息
            this.$http.raw('api/updateTblUr', params).then(res => {
              let { code } = res;
              // 判断Code状态
              if (code === 0) {
                this.$message({
                  message: '修改成功！',
                  type: 'success'
                });
                // 初始化弹出窗表单数据
                this.$refs['editForm'].resetFields();
                // 关闭弹窗
                this.dialogFormVisible = false;
                // 刷新列表
                this.getUsersDataByPage();
                // 获取所有员工
                this.getUsers();
              }
            }).catch(err => {
              if (err === undefined) {
                this.$message({
                  message: '服务器响应异常！',
                  type: 'error'
                });
                return false;
              }
            });
          }
        });
      });
    },

    // 删除
    handleDelete (data) {
      // 二次删除确认
      this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 收集请求参数
        let params = [data.id];
        // 根据数据ID删除对应用户信息
        this.$http.raw('api/batchDelTblUr', params).then(res => {
          let { code } = res;
          if (code === 0) {
            this.$message({
              type: 'success',
              message: '删除成功！'
            });
            // 刷新列表
            this.getUsersDataByPage();
            // 获取所有员工
            this.getUsers();
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 全选、单选、多选
    selsChange: function (sels) {
      this.sels = sels;
    },

    // 批量删除
    batchRemove: function () {
      // 判断是否选择数据
      if (!this.sels.length) {
        this.$message.warning('您还没选择任何数据！');
        return;
      }
      // 二次删除确认
      this.$confirm('确认删除选中的信息吗？', '提示', {
        type: 'warning'
      }).then(() => {
        // 修改状态，逻辑删除
        let params = [];
        // 获取选中数据ID集合
        this.sels.map(item => {
          return params.push(item.id);
        });
        // 删除对应ID用户信息
        this.$http.raw('api/batchDelTblUr', params).then(res => {
          let { code } = res;
          if (code === 0) {
            this.$message({
              type: 'success',
              message: '批量删除成功！'
            });
            // 刷新列表
            this.getUsersDataByPage();
            // 获取所有员工
            this.getUsers();
          }
        }).catch(err => {
          if (err === undefined) {
            this.$message({
              message: '服务器响应异常！',
              type: 'error'
            });
            return false;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 刷新页面数据
    getUsersDataByPage () {
      // 收集请求参数
      let params = {
        deptId: this.formInline.deptId,
        compId: this.formInline.compId,
        roleId: this.formInline.roleId,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      // 获取分页数据
      this.$http.raw('api/findTblUserRoleList', params).then(res => {
        let { code, datas } = res;
        if (code === 0) {
          // 总页数
          this.total = datas.total;
          // 数据结果集
          this.usersData = datas.list;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!datas.list.length && this.currentPage !== 1) {
            // 当前页减一
            this.currentPage -= 1;
            // 调用自己
            this.getUsersDataByPage();
          }
        }
      }).catch(err => {
        if (err === undefined) {
          this.$message({
            message: '服务器响应异常！',
            type: 'error'
          });
          return false;
        }
      });
    },

    // 每页显示的条数改变
    handleSizeChange (val) {
      this.pageSize = val;
      // 调用刷新页面
      this.getUsersDataByPage();
    },
    // 当前页码
    handleCurrentChange (val) {
      this.currentPage = val;
      // 调用
      this.getUsersDataByPage();
    }
  }
};
</script>

<style lang='scss' scoped>
@import './index.scss';
</style>
